//
//  JourneySegmentView.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/2/9.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

public protocol JourneySegmentViewDelegate {
    // 待出行
    func journey_will()
    // 已结束
    func journey_finish()
}

class JourneySegmentView: UIView {
    
    private lazy var orangeLineView:UIView = {
        let ui = UIView()
        ui.layer.cornerRadius = 1.5
        ui.backgroundColor = UIColor.orange
        return ui
    }()
    
    private lazy var willView = UILabel(title: "待出行", color: UIColor.orange)
    private lazy var finishView = UILabel(title: "已结束", color: UIColor.black)
    
    // MARK: 代理
    public var delegate:JourneySegmentViewDelegate?
    
    override func layoutSubviews() {
        // 待出行
        willView.font = UIFont.boldSystemFont(ofSize: 19)
        willView.frame = CGRect(x: MARGIN20, y: 0, width: MARGIN100, height: frame.height)
        addSubview(willView)
        willView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickWill)))
        // 黄色下划线
        orangeLineView.frame.origin = CGPoint(x: MARGIN20, y: frame.height - MARGIN15)
        let w = willView.text!.boundingRect(w: MARGIN100, h: MARGIN70, fontSize: 19).width
        orangeLineView.frame = CGRect(x: MARGIN20, y: frame.height - 13, width: w, height: 3)
        addSubview(orangeLineView)
        // 已结束
        finishView.font = UIFont.boldSystemFont(ofSize: 19)
        finishView.frame = CGRect(x: MARGIN140, y: 0, width: MARGIN100, height: frame.height)
        addSubview(finishView)
        finishView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickFinish)))
    }
    
    @objc func clickWill() -> Void {
        delegate?.journey_will()
        changeView(from: 170, to: 50, orangelabel: willView, blacklabel: finishView)
    }
    
    @objc func clickFinish() -> Void {
        delegate?.journey_finish()
        changeView(from: 20, to: 170, orangelabel: finishView, blacklabel: willView)
    }
    
    private func changeView(from:CGFloat,to:CGFloat,orangelabel:UILabel,blacklabel:UILabel) -> Void {
        if orangelabel.textColor == UIColor.orange {
            return
        }
        // 下滑线滑动
        let animation = CABasicAnimation(keyPath: "position.x")
        animation.toValue = to
        animation.fromValue = from
        animation.fillMode = .forwards
        animation.duration = 0.1
        animation.isRemovedOnCompletion = false
        orangeLineView.layer.add(animation, forKey: nil)
        // 文本颜色改变
        blacklabel.textColor = UIColor.black
        orangelabel.textColor = UIColor.orange
    }
    
    public func selectIndex() -> Int {
        if willView.textColor == UIColor.orange {
            return 0
        }
        return 1
    }
}
